package com.icangya.DAO.impl;


import com.icangya.DAO.IBalanceDAO;
import com.icangya.domain.Balance;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Repository
public class BalanceDAOImpl extends  BaseDAO<Balance> implements IBalanceDAO {


    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Balance getBanlanceByOpenId(String openId) {

        String hql="FROM Balance b where b.openId=?";
        List<Balance> list= (List<Balance>) getHibernateTemplate().find(hql,openId);
        if (list != null && list.size() > 0)
            return list.get(0);
        return null;
    }



    @Override
    public int updateBanlanceByMoney(String openId, double money) {

        int result=getHibernateTemplate().execute(new HibernateCallback<Integer>() {
            @Override
            public Integer doInHibernate(Session session) throws HibernateException {
                String hql="update Balance b set b.money=b.money+? ,b.modifiedTime=? where b.openId=?";

                Query queryData=session.createQuery(hql);

                queryData.setParameter(0,money);
                queryData.setParameter(1,new Timestamp(new Date().getTime()));
                queryData.setParameter(2,openId);
                int ret=queryData.executeUpdate();
                logger.warn("修改金额为 == " + money + "|修改用户openId是 == " + openId + "|结果 == "
                        + ret);
                return ret;
            }
        });

        return result;

    }

  /*  @Override
    public int updateBanlanceByComm(String openId, double money) {

       int result= getHibernateTemplate().execute(new HibernateCallback<Integer>() {

            @Override
            public Integer doInHibernate(Session session) throws HibernateException {

                String hql="update Banlance b set b.commission=b.commission+? where b.openId=?";

                Query queryData=session.createQuery(hql);

                queryData.setParameter(0,money);
                queryData.setParameter(1,openId);
                int ret=queryData.executeUpdate();
                logger.warn("修改佣金为 == " + money + "|修改用户openId是 == " + openId + "|结果 == "
                        + ret);
                return ret;
            }
        });

        return result;
    }*/


}
